<?php

namespace app\service;

use app\common\model\Plugin;
use app\common\model\ThirdUser;
use app\common\model\Users;
use app\model\Config;
use think\Collection;
use think\Request;

abstract class PlatformBaseService
{


    public function __construct()
    {

    }

    /**
     * @return array|\think\Model
     */
    public function loginByPhone()
    {
        $mpCode = \request()->param('mp_code');

        if (!$mpCode) {
            abort(400, '缺少code参数');
        }

        $result = $this->parseCode($mpCode);

        $thirdUser = ThirdUser::where('openid', $result['openid'])->findOrEmpty();
        $thirdUser->openid = $result['openid'];
        $thirdUser->unionid = $result['unionid'] ?? '';
        $thirdUser->platform = request()->header('platform', request()->param('platform'));


        if ($this instanceof WechatOfficialService) {
            $user = $thirdUser->user ?: new Users();
            $user->nickname = '牧场用户-' . mt_rand(1, 1000);
        } else {
            $phone = $this->getPhoneNumber();
            $user = Users::where('mobile', $phone)->findOrEmpty();

            if ($user->mobile && $user->mobile !== $phone) {
                abort(400, '该手机号已经被注册');
            }

            $user->mobile = $phone;
            $user->nickname = $phone;
        }

        if ($user->getKey() && $thirdUser->uid && $user->getKey() !== $thirdUser->uid) {
            abort(400, '该账号已经被注册');
        }

        $user->rekey = getReKey();
        $user->token = getToken();
        $user->save();

        $thirdUser->uid = $user->getKey();
        $thirdUser->save();

        return $user;
    }

    /**获取平台支付方式
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPayMethods(): Collection
    {
        $sceneMap = [
            PlatFormFactory::APP      => 3,
            PlatFormFactory::WECHAT   => 4,
            PlatFormFactory::BYTE     => 5,
            PlatFormFactory::OFFICIAL => 6,
        ];

        return Plugin::where('type', 'payment')
            ->where('status', 1)
            ->where('scene', $sceneMap[$this->platform])
            ->select();
    }

    public static function isApp(): bool
    {
        return request()->param('platform') === PlatFormFactory::APP;
    }

    public function getConfig($key = null)
    {
        return $key ? $this->config[$key] : $this->config;
    }
}